//
// Created on 2024/8/3.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#ifndef SHORT_VIDEO_PLAYER_H
#define SHORT_VIDEO_PLAYER_H

#include <native_image/native_image.h>
#include <thread>
#include "av_codec_sample_log.h"
#include "dfx/error/av_codec_sample_error.h"
#include "sample_info.h"
#include "demuxer.h"
#include "video_decoder.h"
#include "video_encoder.h"
#include "muxer.h"

class Player {
public:
    ~Player();
    explicit Player(int id, OHNativeWindow* window) : instanceId(id), window(window), currentPosition(0) {}
    void Kill();
    int32_t Init(SampleInfo &sampleInfo);
    int32_t Start();
    int32_t Pause();
    int32_t Seek(int64_t position);
    int32_t Resume();
    int32_t Loop(bool loopFlag);
    int32_t GetInstanceId() const;
    int32_t WaitForDone();
    int64_t GetCurrentPosition();
    
private:
    void VideoDecInputThread();
    void VideoDecOutputThread();
    void Release();
    void StartRelease();
    int32_t CreateVideoDecoder();
    
    void SetSurfaceToConsumerSurface();

    std::unique_ptr<VideoDecoder> videoDecoder_ = nullptr;
    std::unique_ptr<Demuxer> demuxer_ = nullptr;
    
    std::mutex mutex_;
    std::atomic<bool> isStarted_ { false };
    std::atomic<bool> isPause_ { false };
    std::atomic<bool> isLoop_ { true };
    std::atomic<bool> isExitSignal_{false};
    std::unique_ptr<std::thread> videoDecInputThread_ = nullptr;
    std::unique_ptr<std::thread> videoDecOutputThread_ = nullptr;
    std::unique_ptr<std::thread> releaseThread_ = nullptr;
    std::condition_variable doneCond_;
    SampleInfo sampleInfo_;
    CodecUserData *videoDecContext_ = nullptr;
    static constexpr int64_t MICROSECOND = 1000000;
    static constexpr int64_t MILLISECONDS = 1000;
    int32_t instanceId;
    OHNativeWindow* window;
    int64_t currentPosition;
};

#endif // SHORT_VIDEO_PLAYER_H
